package com.copd.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.http.HttpMethod;

import java.util.Arrays;
import java.util.Collections;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtRequestFilter jwtRequestFilter;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
            .cors(cors -> cors.configurationSource(corsConfigurationSource()))
            .csrf(AbstractHttpConfigurer::disable)
            .authorizeRequests(auth -> auth
                // 允许所有OPTIONS请求
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                // 允许登录和注册接口
                .antMatchers("/api/users/login", "/api/users/register").permitAll()
                
                // 特别设置: 明确允许所有患者接口，比其他规则优先级更高
                .antMatchers("/api/patients", "/api/patients/**").permitAll()
                
                // 基本用户接口 - 允许所有已认证用户访问
                .antMatchers("/api/users/current").authenticated()
                .antMatchers("/api/roles/user/{userId}").authenticated()
                .antMatchers("/api/users/{userId}/permissions").authenticated()
                .antMatchers(HttpMethod.PUT, "/api/users/{userId}/permissions").hasRole("admin")
                
                // 诊疗记录相关接口 - 允许所有已认证用户访问
                .antMatchers(HttpMethod.GET, "/api/medical-records/**").authenticated()
                .antMatchers(HttpMethod.POST, "/api/medical-records/**").authenticated()
                .antMatchers(HttpMethod.PUT, "/api/medical-records/**").authenticated()
                .antMatchers(HttpMethod.DELETE, "/api/medical-records/**").authenticated()
                
                // 数据分析相关接口 - 允许所有已认证用户访问
                .antMatchers(HttpMethod.GET, "/api/analysis/**").authenticated()
                .antMatchers("/api/analysis/export/**").authenticated()
                
                // 系统管理相关接口 - 仅允许管理员访问
                .antMatchers("/api/backup/**", "/api/backups/**").hasRole("admin")
                .antMatchers("/api/config/**").hasRole("admin")
                
                // 权限管理相关接口 - 仅允许管理员访问
                .antMatchers("/api/permissions/**").hasRole("admin")
                .antMatchers("/api/roles/**").hasRole("admin")
                .antMatchers("/api/user-roles/**").hasRole("admin")
                
                // 允许Swagger UI相关路径
                .antMatchers("/swagger-ui.html", "/swagger-resources/**", "/v2/api-docs", "/webjars/**").permitAll()
                
                // 其他所有请求需要认证
                .anyRequest().authenticated()
            )
            .sessionManagement(session -> session
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            )
            // 添加JWT过滤器
            .addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class)
            .build();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOriginPatterns(Collections.singletonList("*"));  // 允许所有来源
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setExposedHeaders(Arrays.asList("Authorization"));
        configuration.setMaxAge(3600L);
        
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
} 